package com.helloworld.demo.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest5 {

    private static Lock lock = new ReentrantLock();

    private static Condition cigCon = lock.newCondition();

    private static Condition takeCon = lock.newCondition();

    private static boolean hasCigCon = false;

    private static boolean hasTakeCon = false;


    public void cigratee(){
        lock.lock();
        try {
            while (!hasCigCon){
                try{
                    System.out.println("无烟阻塞");
                    cigCon.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            System.out.println("有烟执行");
        } finally {
            lock.unlock();
        }
    }


    public void takeOut(){
        lock.lock();
        try{
            while (!hasTakeCon){
                try {
                    System.out.println("无饭阻塞");
                    takeCon.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            System.out.println("有饭执行");
        }finally {
            lock.unlock();
        }
    }

    public void productCigratee(){
        lock.lock();
        try{
            hasCigCon = true;
            System.out.println("造烟成功");
            cigCon.signal();
        }finally {
            lock.unlock();
        }
    }


    public void productTakeOut(){
        lock.lock();
        try{
            hasTakeCon = true;
            System.out.println("造饭成功");
            takeCon.signal();
        }finally {
            lock.unlock();
        }
    }



    public static void main(String[] args) throws InterruptedException {
        ReentrantLockTest5 reentrantLockTest5 = new ReentrantLockTest5();

        new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLockTest5.cigratee();
            }
        }).start();

        new Thread(()->{
            reentrantLockTest5.takeOut();
        }).start();

        Thread.sleep(1000);

        new Thread(()->{
            reentrantLockTest5.productCigratee();
        }).start();

        new Thread(()->{
            reentrantLockTest5.productTakeOut();
        }).start();




    }

}
